package com.xbongbong.paas.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.xbongbong.paas.pojo.dto.ActiveRuleDTO;
import com.xbongbong.paas.service.ExecuteBusinessRuleService;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.wrap.XbbResponse;
import com.xbongbong.pro.businessproduct.pojo.vo.BusinessProductListVO;
import com.xbongbong.pro.constant.XbbProConstant;
import com.xbongbong.pro.enums.errorcodes.SystemErrorCodeEnum;
import org.springframework.http.MediaType;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.Objects;

/**
 * @author 吴峰
 * @date 2021/10/28 14:21
 */
@RestController
@RequestMapping(value = XbbProConstant.API_ROOT_PREFIX + "/businessRule")
public class BusinessRuleController {

    @Resource
    private ExecuteBusinessRuleService executeBusinessRuleService;

    /**
     * 新建或者编辑触发生效规则执行
     *
     * @param activeRuleDTO
     * @author 吴峰
     * @date 2021/10/28 14:23
     * @since v1.0
     * @return java.lang.String
     **/
    @RequestMapping(value = "/activeRule", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public String businessProductListGet(@RequestBody @Valid ActiveRuleDTO activeRuleDTO, BindingResult br) {
        XbbResponse<BusinessProductListVO> response;
        if (br.hasErrors()) {
            String errMsg = Objects.requireNonNull(br.getFieldError()).getDefaultMessage();
            response = new XbbResponse<>(SystemErrorCodeEnum.API_ERROR_100002, errMsg);
        } else {
            try {

                executeBusinessRuleService.execute(activeRuleDTO);
                response = new XbbResponse<>();
            } catch (XbbException e) {
                response = new XbbResponse<>(e);
            }
        }
        return JSON.toJSONString(response, SerializerFeature.DisableCircularReferenceDetect);
    }
}
